package org.pi.common.geom

object Geom {
  private def convertPointPolygonToStraights(l: List[Point]) = (for (index : Int <- 0 to (l.size-1)) yield Straight(l(index), l((index+1)%l.size))).toList
  
  private def isPointLeftOfStraights(p: Point, l:List[Straight]) = (for(s <- l) yield (s signedDistance p)<0).toList
  private def getFoldedAndOrOfBooleanList(l:List[Boolean]) = l.foldLeft[Tuple2[Boolean,Boolean]]( (l(0),l(0)) ) ( (a,b) => (a._1||b, a._2&&b) )  
  private def hasBooleanTupleIndeticalEntries(t: Tuple2[Boolean,Boolean]) = (t._1 == t._2)
  def isPointInConvexPolygon(p: Point,l: List[Point]) = hasBooleanTupleIndeticalEntries(getFoldedAndOrOfBooleanList(isPointLeftOfStraights(p, convertPointPolygonToStraights(l)))) 

  def isPointInConvexPolygon2(p: Point,l: List[Point]) = {
    var straights = convertPointPolygonToStraights(l)
    var isMyPointLeftofFirstStraight = ((straights(0) signedDistance p)<0)
    var areAllPointsOnTheSameSide = true
    straights.foreach( s => if ((straights(0) signedDistance p)>=0) areAllPointsOnTheSameSide = false )
    areAllPointsOnTheSameSide // return value
  }
}

object GeomMain {
  def main(args: Array[String]) {
    def l = Point(0,0) :: Point(1,1) :: Point(1,0) :: Nil;
    println(l)
    
    println("(0.5f, 0.25f) must be in the poly: "+ Geom.isPointInConvexPolygon( Point(0.5f, 0.25f), l) )
    println("(-0.5f, 0.25f) must not be in the poly: "+ Geom.isPointInConvexPolygon( Point(-0.5f, 0.25f), l) )
    println("alternative impl.:")
    println("(0.5f, 0.25f) must be in the poly: "+ Geom.isPointInConvexPolygon2( Point(0.5f, 0.25f), l) )
    println("(-0.5f, 0.25f) must not be in the poly: "+ Geom.isPointInConvexPolygon2( Point(-0.5f, 0.25f), l) )
  }
}
